package xyz.hujf.otherbase.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Hujf
 * @title: ReentrantLockTest
 * @date 2021-04-2416:37
 * @description: TODO
 * <p>
 * 可重入锁
 * 同一线程外层函数获得锁之后，内层递归函数仍能获得该所的代码
 * 在同一线程在外层方法获得锁的时候，在进入内层方法会自动获得锁
 */

class Phone implements Runnable{

    public synchronized void sendMs() {
        System.out.println(Thread.currentThread().getId() + "\t invoke sendMs");
        sendMail();
    }

    public synchronized void sendMail() {
        System.out.println(Thread.currentThread().getId() + "\t invoke send mail");
    }

    Lock lock = new ReentrantLock();
    @Override
    public void run() {
        get();
    }

    public void get(){
        lock.lock();
        System.out.println(Thread.currentThread().getName() + "\t invoke sendMs");
        set();
        lock.unlock();
    }

    public void set(){
        lock.lock();
        System.out.println(Thread.currentThread().getName() + "\t invoke send mail");
        lock.unlock();
    }

}

public class ReentrantLockTest {

    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(() -> {
            phone.sendMs();
        }, "t1").start();

        new Thread(()->{

            phone.sendMs();
        },"t2").start();


        Thread t3 = new Thread(phone,"t3");
        Thread t4 = new Thread(phone,"t4");
        t3.start();
        t4.start();
    }
}
